import dayjs from 'dayjs';
import dayOfYear from 'dayjs/plugin/dayOfYear';
dayjs.extend(dayOfYear);
import customParseFormat from 'dayjs/plugin/customParseFormat';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(customParseFormat);
dayjs.extend(relativeTime);

const testTimestramp = /^\d+$/;
// const DAY = 86400;

/**
 * 精确到天的时间加减(忽略时分秒) 支持时间戳与yyyy-mm-dd的格式
 * @param subtractedTime 被减数
 * @param minusTime 减数
 * @return 相减获得的新时间 [是否为负数,相差的天数]
 */
export const timeMinus = (subtractedTime: string | number, minusTime: string | number) => {
  let subtractedTimeTmp: dayjs.Dayjs;
  let minusTimeTmp: dayjs.Dayjs;
  const subtractedTimeTmpString = subtractedTime?.toString();
  const minusTimeTmpString = minusTime?.toString();
  if (testTimestramp.test(subtractedTimeTmpString)) {
    if (subtractedTimeTmpString.length === 13) {
      subtractedTimeTmp = dayjs(subtractedTime);
    } else {
      subtractedTimeTmp = dayjs.unix(+subtractedTime);
    }
  } else {
    subtractedTimeTmp = dayjs(subtractedTime, 'YYYY-MM-DD');
  }
  if (testTimestramp.test(minusTimeTmpString)) {
    if (minusTimeTmpString.length === 13) {
      minusTimeTmp = dayjs(minusTime);
    } else {
      minusTimeTmp = dayjs.unix(+minusTime);
    }
  } else {
    minusTimeTmp = dayjs(minusTime, 'YYYY-MM-DD');
  }
  let tmp = subtractedTimeTmp.unix() - minusTimeTmp.unix();
  let flag = 1;
  if (tmp < 0) {
    flag = -1;
    tmp = Math.abs(tmp);
  }
};

export const handleGetMonthTimestamp = (subtractMonth: number) => {
  const subtract = dayjs().subtract(subtractMonth, 'month');
  const startTimestamp = subtract.startOf('month').unix();
  const startFormat = subtract.startOf('month').format('MM/DD');
  const endTimestamp = subtract.endOf('month').unix();
  const endFormat = subtract.endOf('month').format('MM/DD');
  const dateFormat = subtract.format('YYYY年MM月');
  const daysInMonth = subtract.daysInMonth();
  const monthValue = subtract.startOf('month').format('MM');

  return { startTimestamp, endTimestamp, dateFormat, daysInMonth, startFormat, endFormat, monthValue };
};

export const handleGetYearOrMonthTimestamp = (subtractData: number, type: 'month' | 'year') => {
  const subtract = dayjs().subtract(subtractData, type);
  const startTimestamp = subtract.startOf(type).unix();
  const endTimestamp = subtract.endOf(type).unix();
  const dateFormat = type === 'month' ? subtract.format('YYYY年MM月') : subtract.format('YYYY年');
  const daysInType = type === 'month' ? subtract.daysInMonth() : subtract.endOf('year').dayOfYear();
  return { startTimestamp, endTimestamp, dateFormat, daysInType };
};
